# _*_ coding:utf-8 _*_
import time
import os
import subprocess
import _thread
import base64
from utils import request_utils
import datetime


def get_process_count(process_name):
    p = os.popen('tasklist /FI "IMAGENAME eq %s"' % process_name)
    return p.read().count(process_name)


# 为线程定义一个函数
def start_up_process(process_path='', open_id='', delay=0):
    process_name = process_path.split('\\')[-1]
    while True:
        # print(get_process_count(process_name))
        if get_process_count(process_name) == 0:
            # print(process_path)
            subprocess.Popen(process_path, True)
            url = 'http://weixin.voiceads.cn/apiNotice?t=v89qN9S3v2uMMJG'
            headers = {'content-type': 'application/json'}
            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            param_str = r'{   "summary":"服务重启",   "businessType":"服务重启",   "businessStatus":"' + current_time + '",   "businessContent":"服务中断",   "openid":[       "' + open_id + '"   ],   "remark":"重启成功",   "url":"" }'
            data = base64.b64encode(param_str.encode('utf-8'))
            data = str(data, 'utf-8')
            request_utils.post(url, {"data": data}, headers)
            # Popen(r'C:\Users\admin\AppData\Local\Programs\飞鸽客服工作台\飞鸽客服工作台.exe', shell=True)
        time.sleep(delay)
        # print(threadName)
        # time.sleep(delay)
        # print("%s: %s" % (threadName, time.ctime(time.time())))


# 开启线程
def start(process_path='', open_id='', delay=10):
    # process_path = r'D:\D_apps\飞鸽客服工作台\飞鸽客服工作台.exe'
    # 创建两个线程
    try:
        _thread.start_new_thread(start_up_process, (process_path, open_id, delay))
    except:
        print("Error: 无法启动线程")


if __name__ == "__main__":
    process_path = r'D:\D_apps\飞鸽客服工作台\飞鸽客服工作台.exe'
    process_name = '飞鸽客服工作台.exe'
    print(process_path.split('\\')[-1])
    # process_name = '飞鸽客服工作台.exe'
    # process_path = r'D:\D_apps\飞鸽客服工作台\飞鸽客服工作台.exe'
    # delay = 5
    # # 创建两个线程
    # try:
    #     _thread.start_new_thread(start_up_process, (process_name, process_path, delay))
    # except:
    #     print("Error: 无法启动线程")
    # while True:
    #     pass
